<?php namespace App\Http\Controllers;

use App\Models\Admin as MAdmin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Admin extends Controller
{
    public function index(Request $request)
    {
        $page = $request->input('page');
        $query = DB::table('admins')
            ->select('*');
        if ($filterText = $request->input('filter.text')) {
            $query->where(function ($query) use ($filterText) {
                $query->where('admins.username', 'like', '%' . $filterText . '%')
                    ->orWhere('admins.nickname', 'like', '%' . $filterText . '%')
                    ->orWhere('admins.phone', 'like', '%' . $filterText . '%')
                    ->orWhere('admins.email', 'like', '%' . $filterText . '%');
            });
        }
        return $query->paginate($page['size'], ['*'], 'page', $page['current']);
    }

    //获取管理员对象
    public function show($id)
    {
        $admin = MAdmin::find($id);
        return response()->json($admin);
    }

    //添加管理员
    public function store(Request $request)
    {
        // 表单验证，配合前台验证
        $this->validate($request, [
            'username' => 'unique:admins',
            'phone' => 'unique:admins',
            'email' => 'unique:admins',
            'password' => 'required'
        ]);
        $admin = new MAdmin;
        $admin->username = $request->input('username');
        $admin->phone = $request->input('phone');
        $admin->email = $request->input('email');
        $admin->nickname = $request->input('nickname');
        $admin->address = $request->input('address');
        $admin->password = bcrypt($request->input('password'));
        $admin->save();
        return response()->json($admin->id);
    }

    //修改管理员
    public function update(Request $request, $id)
    {
        // 表单验证，配合前台验证
        $this->validate($request, [
            'username' => 'unique:admins,username,' . $id,
            'phone' => 'unique:admins,phone,' . $id,
            'email' => 'unique:admins,email,' . $id
        ]);

        $admin = MAdmin::find($id);
        assert($admin);
        $admin->username = $request->input('username');
        $admin->phone = $request->input('phone');
        $admin->email = $request->input('email');
        $admin->nickname = $request->input('nickname');
        $password = $request->input('password');
        if ($password != null)
            $admin->password = bcrypt($password);
        $admin->address = $request->input('address');
        $admin->save();
        return response('', 200);
    }

    //删除管理员
    public function destroy($id)
    {
        $admin = MAdmin::find($id);
        if (!$admin) {
            return response('传参错误，未找到对象！', 500);
        }
        $admin->delete();
        return response('', 200);
    }
}
